package org.leetcode.medium;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> list1 = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 1 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1;
            int x = nums.length - 1;
            int target = -nums[i];
            while (j < x) {
                if(j > i + 1 && nums[j] == nums[j - 1]) {
                    j++;
                    continue;
                }
                //
                while (j < x && nums[j] + nums[x] > target) {
                    x--;
                }
                if (j < x && nums[j] + nums[x] == target) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[x]);
                    list1.add(list);
                }
                j++;
            }
        }
        return list1;
    }

    @Test
    public void test() {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        System.out.println(threeSum(nums));
    }
}
